<script setup>
import { ref, computed, watch, defineProps, defineEmits, inject, defineExpose, nextTick } from 'vue'
import { ElButton, ElInput, ElDatePicker, ElSelect, ElInputNumber, ElTag, ElIcon, ElMessage, ElRate } from 'element-plus'
import { Close, More } from '@element-plus/icons-vue'
import IconSvg from '../icons/IconSvg.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  item: {
    type: Object,
    default: () => ({})
  },
  categories: {
    type: Array,
    default: () => []
  },
  locations: {
    type: Array,
    default: () => []
  },
  statuses: {
    type: Array,
    default: () => []
  },
  icons: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'save', 'open-icon-selector', 'refresh'])

const localItem = ref({})
const detailLoading = ref(false) // 控制加载状态
const editingLocation = ref(false)
const editingBrand = ref(false)
const brandInput = ref(null)
const editingSpecification = ref(false)
const specificationInput = ref(null)
const editingPrice = ref(false)
const priceInput = ref(null)
const editingExpiryDate = ref(false)
const editingPurchaseChannel = ref(false)
const purchaseChannelInput = ref(null)
const editingRating = ref(false)
const ratingInput = ref(null)
const editingPurchaseDate = ref(false)
const editingStatus = ref(false) // 添加状态编辑状态变量
const editingQuantity = ref(false) // 添加数量编辑状态变量
const quantityInput = ref(null) // 添加数量输入框引用

// 计算属性，获取当前分类名称 - 直接依赖 props
const currentCategoryName = computed(() => {
  return getCategoryName(props.item?.categoryId)
})

// 监听外部传入的 item 变化，更新本地副本
watch(() => props.item, (newItem) => {
  if (newItem && props.visible) { // 只有在弹窗可见且有新 item 时才更新
    detailLoading.value = true // 开始加载
    // 模拟异步加载
    setTimeout(() => {
      // 使用深拷贝防止直接修改原始对象
      localItem.value = JSON.parse(JSON.stringify(newItem))
      detailLoading.value = false // 加载完成
    }, 100) // 减少延迟以提高响应速度
  } else {
    localItem.value = {}
  }
}, { immediate: true, deep: true }) // 添加deep: true以确保检测到对象内部的变化

// 监听可见性变化
watch(() => props.visible, (newValue) => {
  if (!newValue) {
    // 弹窗关闭，不需要特别处理
  } else {
    // 当弹窗打开时，重新加载数据（如果item已经存在）
    if (props.item && props.item.id) {
      detailLoading.value = true;
      setTimeout(() => {
        localItem.value = JSON.parse(JSON.stringify(props.item))
        detailLoading.value = false;
      }, 300);
    }
  }
});

// 监听编辑状态，自动聚焦
watch(editingLocation, (newVal) => {
  if (newVal) {
    nextTick(() => {
      // 下拉菜单不需要手动聚焦
    })
  }
})

watch(editingBrand, (newVal) => {
  if (newVal) {
    nextTick(() => {
      brandInput.value?.focus()
    })
  }
})

watch(editingSpecification, (newVal) => {
  if (newVal) {
    nextTick(() => {
      specificationInput.value?.focus()
    })
  }
})

watch(editingPrice, (newVal) => {
  if (newVal) {
    nextTick(() => {
      priceInput.value?.focus()
    })
  }
})

watch(editingPurchaseChannel, (newVal) => {
  if (newVal) {
    nextTick(() => {
      purchaseChannelInput.value?.focus()
    })
  }
})

watch(editingRating, (newVal) => {
  if (newVal) {
    nextTick(() => {
      ratingInput.value?.focus()
    })
  }
})

watch(editingPurchaseDate, (newVal) => {
  if (newVal && !newVal.focus) {
    // 日期选择器不需要聚焦
  }
})

watch(editingExpiryDate, (newVal) => {
  if (newVal && !newVal.focus) {
    // 日期选择器不需要聚焦
  }
})

watch(editingQuantity, (newVal) => {
  if (newVal) {
    nextTick(() => {
      quantityInput.value?.focus()
    })
  }
})

// 新增：专门监听 categoryId 和 iconId 的变化
watch(() => props.item?.categoryId, (newVal, oldVal) => {
  console.log(`[Modal] Watched props.item.categoryId changed from ${oldVal} to ${newVal}`);
});

watch(() => props.item?.iconId, (newVal, oldVal) => {
  console.log(`[Modal] Watched props.item.iconId changed from ${oldVal} to ${newVal}`);
});

// 获取状态名称
const getStatusName = (statusValue) => {
  const status = props.statuses.find(s => s.value === statusValue)
  return status ? status.label : null
}

// 获取位置名称
const getLocationName = (locationId) => {
  const location = props.locations.find(l => l.id === locationId)
  return location ? location.name : null
}

// 处理位置变更
const handleLocationChange = () => {
  // 当用户选择新的位置时，更新 specificLocation 字段
  const selectedLocationName = getLocationName(localItem.value.locationId);
  if (selectedLocationName) {
    localItem.value.specificLocation = selectedLocationName;
  }
  // 关闭编辑模式
  editingLocation.value = false;
}

// 根据图标ID获取图标名称
const getIconNameById = (iconId) => {
  if (!iconId) return null
  console.log(`[Modal] getIconNameById called with ID: ${iconId}`);
  const icon = props.icons.find(icon => icon.id === iconId)
  console.log(`[Modal] Found icon object:`, icon);
  const name = icon ? icon.name : null;
  console.log(`[Modal] Returning icon name: ${name}`);
  return name;
}

// 获取图标所属分类
const getIconCategory = (iconId) => {
  if (!iconId) return null
  const icon = props.icons.find(icon => icon.id === iconId)
  return icon ? icon.category : null
}

// 根据图标分类获取对应的物品分类ID
const getCategoryIdByIconCategory = (iconCategory) => {
  // 图标分类与物品分类的映射关系
  const categoryMap = {
    '工具': props.categories.find(c => c.name === '工具')?.id,
    '厨具': props.categories.find(c => c.name === '厨房用品')?.id,
    '数码': props.categories.find(c => c.name === '电器')?.id,
    '家电': props.categories.find(c => c.name === '电器')?.id,
    '首饰': props.categories.find(c => c.name === '装饰品')?.id,
    '美妆': props.categories.find(c => c.name === '卫浴用品')?.id,
    '玩具': props.categories.find(c => c.name === '其他')?.id,
    '运动': props.categories.find(c => c.name === '其他')?.id,
    '交通': props.categories.find(c => c.name === '其他')?.id,
    '服饰': props.categories.find(c => c.name === '其他')?.id
  }
  
  return categoryMap[iconCategory] || null
}

const closeModal = () => {
  emit('update:visible', false)
}

const saveChanges = async () => {
  // 简单的验证示例
  if (!localItem.value.name) {
    ElMessage.error('物品名称不能为空');
    return;
  }
  
  console.log('保存按钮被点击，准备保存物品:', JSON.stringify(localItem.value));
  detailLoading.value = true; // 开始保存时的加载状态
  try {
    // 创建要提交的数据对象，去掉category字段，只保留categoryId
    const itemToSubmit = {...localItem.value};
    
    // 确保删除category字段，不传递给后端
    if ('category' in itemToSubmit) {
      delete itemToSubmit.category;
    }
    
    // 确保有分类ID
    if (!itemToSubmit.categoryId) {
      if (props.item && props.item.categoryId) {
        itemToSubmit.categoryId = props.item.categoryId;
      } else if (props.categories && props.categories.length > 0) {
        itemToSubmit.categoryId = props.categories[0].id;
        console.log('使用默认分类ID:', itemToSubmit.categoryId);
      } else {
        ElMessage.warning('未指定物品分类');
      }
    }
    
    // 确保locationId字段存在且有效
    if (!itemToSubmit.locationId) {
      // 首先尝试使用父组件传递的当前位置
      if (props.item && props.item.locationId) {
        itemToSubmit.locationId = props.item.locationId;
        console.log('使用当前编辑的物品位置ID:', itemToSubmit.locationId);
      } else {
        // 尝试从localStorage获取当前位置ID
        const currentLocationId = localStorage.getItem('currentLocationId');
        if (currentLocationId) {
          // 确保位置ID是数字类型
          itemToSubmit.locationId = parseInt(currentLocationId) || currentLocationId;
          console.log('从localStorage获取位置ID:', itemToSubmit.locationId);
        } else if (props.locations && props.locations.length > 0) {
          // 如果没有位置ID，使用第一个可用位置
          itemToSubmit.locationId = props.locations[0].id;
          console.log('使用第一个可用位置ID:', itemToSubmit.locationId);
        }
      }
    }
    
    // 添加位置名称信息
    if (itemToSubmit.locationId) {
      const locationObj = props.locations.find(l => l.id === itemToSubmit.locationId);
      if (locationObj) {
        itemToSubmit.locationName = locationObj.name;
        itemToSubmit.specificLocation = locationObj.name;
      }
    }
    
    // 确保purchaseChannel字段已设置
    if (itemToSubmit.purchasePlatform && !itemToSubmit.purchaseChannel) {
      itemToSubmit.purchaseChannel = itemToSubmit.purchasePlatform;
    }
    
    console.log('准备向父组件提交数据:', JSON.stringify(itemToSubmit));
    
    // 移除await，emit是同步函数不返回Promise
    emit('save', itemToSubmit);
    console.log('emit save事件已触发，等待父组件处理');
    
    // 保存成功后关闭弹窗
    emit('update:visible', false);
    // 发送刷新信号
    emit('refresh');
  } catch (error) {
    console.error("Save error:", error);
    ElMessage.error('保存失败');
  } finally {
    detailLoading.value = false; // 结束加载状态
  }
}

// 格式化日期显示
const formatDateDisplay = (dateStr) => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN')
  } catch (e) {
    return dateStr // 如果格式错误，返回原始字符串
  }
}

// 计算物品拥有天数
const getOwnedDays = (item) => {
  if (!item.purchaseDate) return 0
  const purchaseDate = new Date(item.purchaseDate)
  const today = new Date()
  const diffTime = Math.abs(today - purchaseDate)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 计算物品每日成本
const getDailyCost = (item) => {
  const days = getOwnedDays(item)
  if (days === 0 || !item.price) return '0.00'
  return (item.price / days).toFixed(2)
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '-'
  console.log(`[Modal] getCategoryName called with ID: ${categoryId}`);
  console.log(`[Modal] props.categories:`, JSON.stringify(props.categories));
  const category = props.categories.find(c => c.id === categoryId)
  console.log(`[Modal] Found category object:`, category);
  const name = category ? category.name : '-'
  console.log(`[Modal] Returning name: ${name}`);
  return name;
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'active': return 'success'
    case 'inactive': return 'info'
    case 'disposed': return 'danger'
    default: return 'info'
  }
}

// 打开图标选择器
const openIconSelector = () => {
  emit('open-icon-selector', localItem.value)
}

// 处理从父组件选择图标后的更新
const handleIconUpdate = (updatedItem) => {
  if (updatedItem && updatedItem.iconId) {
    console.log('选择的图标ID:', updatedItem.iconId);
    localItem.value.iconId = updatedItem.iconId
    
    // 获取图标的分类
    const iconCategory = getIconCategory(updatedItem.iconId)
    console.log('图标分类:', iconCategory);
    
    if (iconCategory) {
      // 根据图标分类获取对应的物品分类ID
      const categoryId = getCategoryIdByIconCategory(iconCategory)
      console.log('映射到的分类ID:', categoryId);
      
      if (categoryId) {
        localItem.value.categoryId = categoryId
        console.log('设置物品分类ID:', categoryId);
        
        // 添加成功消息
        const categoryName = getCategoryName(categoryId);
        ElMessage.success(`已根据选择的${iconCategory}图标自动设置分类为: ${categoryName}`);
      }
    }
  }
}

// 暴露方法给父组件
defineExpose({
  handleIconUpdate
})
</script>

<template>
  <transition name="modal" :duration="{ enter: 400, leave: 300 }">
    <div v-if="visible" class="modal-overlay" @click.self="closeModal">
      <div class="modal-container">
        <!-- Header -->
        <div class="modal-header">
          <h2 class="modal-title">物品详情</h2>
          <div class="header-actions">
            <el-button type="primary" class="save-button" @click="saveChanges">保存</el-button>
            <button class="modal-close" @click="closeModal">
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </div>

        <!-- Loading Indicator -->
        <div v-if="detailLoading" class="modal-loading-indicator">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- Content - Always in Edit Mode -->
        <div v-else class="modal-content">
          <!-- 修改：头像和名称横向布局 -->
          <div class="header-layout">
            <!-- 图标 -->
            <div class="icon-box large-icon" @click="openIconSelector" style="cursor: pointer;">
              <IconSvg v-if="props.item?.iconId && getIconNameById(props.item.iconId)" 
                :name="getIconNameById(props.item.iconId)" 
                :size="60" 
                color="#333" 
              />
              <el-icon v-else><More /></el-icon>
              <div class="icon-select-hint">点击选择图标</div>
            </div>
            
            <!-- 名称输入框，使用大标题样式 -->
            <div class="name-input-container">
              <div class="name-title-wrapper">
                <input
                  v-model="localItem.name"
                  type="text"
                  placeholder="请输入名称"
                  class="name-title-input"
                />
            </div>
          </div>

            <!-- 右上角分类和位置 -->
            <div class="top-right-info">
              <!-- Card for Category -->
              <div class="form-card category-form-card">
                <label class="form-card-label">分类</label>
                <div class="location-display">
                  <span v-if="props.item?.iconId && getIconNameById(props.item.iconId)" style="margin-right: 8px;">
                    <IconSvg :name="getIconNameById(props.item.iconId)" :size="20" color="#333" />
                  </span>
                  {{ currentCategoryName || '-' }}
                </div>
              </div>

              <!-- Card for Location -->
              <div class="form-card location-form-card">
                <label class="form-card-label">位置</label>
                <transition name="fade" mode="out-in">
                  <div v-if="!editingLocation" key="display" class="location-display" @click="editingLocation = true">
                    {{ localItem.specificLocation || getLocationName(localItem.locationId) || '-' }}
                  </div>
                  <el-select
                    v-else
                    key="edit"
                    v-model="localItem.locationId"
                    placeholder="请选择位置"
                    @change="handleLocationChange"
                    @blur="editingLocation = false"
                    class="edit-input location-select"
                    size="small"
                    popper-class="location-select-dropdown"
                  >
                  <el-option
                    v-for="location in locations"
                    :key="location.id"
                    :label="location.name"
                    :value="location.id"
                  />
                </el-select>
                </transition>
              </div>
              
              <!-- Card for Price -->
              <div class="form-card input-card">
                <label class="form-card-label">价格</label>
                <div v-if="!editingPrice" class="location-display" @click="editingPrice = true">{{ localItem.price ? `¥${localItem.price}` : '-' }}</div>
                <el-input 
                  v-else
                  v-model="localItem.price" 
                  @blur="editingPrice = false"
                  @keyup.enter="editingPrice = false"
                  ref="priceInput"
                  class="edit-input"
                  size="small"
                />
              </div>
              </div>
            </div>

          <!-- Edit Form using Card Layout -->
          <div class="edit-form">
            <!-- 移除了单独的名称卡片，因为已经并入上方布局 -->

            <!-- Row 2: Brand & Specification Cards -->
            <div class="info-row-group">
              <!-- Card for Brand -->
              <div class="form-card input-card">
                <label class="form-card-label">品牌</label>
                <div v-if="!editingBrand" class="location-display" @click="editingBrand = true">{{ localItem.brand || '-' }}</div>
                <el-input 
                  v-else
                  v-model="localItem.brand" 
                  @blur="editingBrand = false"
                  @keyup.enter="editingBrand = false"
                  ref="brandInput"
                  class="edit-input"
                  size="small"
                />
              </div>

              <!-- Card for Specification -->
              <div class="form-card input-card">
                <label class="form-card-label">规格</label>
                <div v-if="!editingSpecification" class="location-display" @click="editingSpecification = true">{{ localItem.specification || '-' }}</div>
                <el-input 
                  v-else
                  v-model="localItem.specification" 
                  @blur="editingSpecification = false"
                  @keyup.enter="editingSpecification = false"
                  ref="specificationInput"
                  class="edit-input"
                  size="small"
                />
              </div>
            </div>

            <!-- Row 3: Price & Purchase Date Cards -->
            <div class="info-row-group">
              <!-- Card for Expiry Date -->
              <div class="form-card date-input-card">
                <label class="form-card-label">过期时间</label>
                <div v-if="!editingExpiryDate" class="location-display" @click="editingExpiryDate = true">{{ localItem.expiryDate ? formatDateDisplay(localItem.expiryDate) : '-' }}</div>
                <el-date-picker
                  v-else
                  v-model="localItem.expiryDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  placeholder="选择日期"
                  @change="editingExpiryDate = false"
                  class="edit-input date-picker"
                  size="small"
                />
              </div>

              <!-- Card for Purchase Date -->
              <div class="form-card date-input-card">
                <label class="form-card-label">购买日期</label>
                <div v-if="!editingPurchaseDate" class="location-display" @click="editingPurchaseDate = true">
                  {{ localItem.purchaseDate ? formatDateDisplay(localItem.purchaseDate) : '-' }}
                </div>
                <el-date-picker
                  v-else
                  v-model="localItem.purchaseDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  placeholder="选择日期"
                  @change="editingPurchaseDate = false"
                  class="edit-input date-picker"
                  size="small"
                />
              </div>
            </div>
            
            <!-- Row 4: Purchase Platform & Rating -->
            <div class="info-row-group">
              <!-- Card for Purchase Platform -->
              <div class="form-card input-card">
                <label class="form-card-label">购买平台</label>
                <div v-if="!editingPurchaseChannel" class="location-display" @click="editingPurchaseChannel = true">{{ localItem.purchaseChannel || localItem.purchasePlatform || '-' }}</div>
                <el-input 
                  v-else
                  v-model="localItem.purchaseChannel" 
                  @blur="editingPurchaseChannel = false"
                  @keyup.enter="editingPurchaseChannel = false"
                  ref="purchaseChannelInput"
                  class="edit-input"
                  size="small"
                />
              </div>
              
              <!-- Card for Rating -->
              <div class="form-card input-card">
                <label class="form-card-label">评分</label>
                <div v-if="!editingRating" class="location-display" @click="editingRating = true">{{ localItem.rating ? `${localItem.rating}分` : '-' }}</div>
                <el-input 
                  v-else
                  v-model="localItem.rating" 
                  @blur="editingRating = false"
                  @keyup.enter="editingRating = false"
                  ref="ratingInput"
                  class="edit-input"
                  size="small"
                />
              </div>
            </div>

            <!-- Row 5: Generated Fields (Daily Cost & Owned Days) - Read Only -->
            <div class="info-row-group">
              <div class="form-card readonly-card">
                <label class="form-card-label">每日成本</label>
                <div class="form-card-value">¥{{ getDailyCost(localItem) }}/天</div>
              </div>
              <div class="form-card readonly-card">
                <label class="form-card-label">持有天数</label>
                <div class="form-card-value">{{ getOwnedDays(localItem) }}天</div>
              </div>
            </div>

            <!-- 状态、消耗品和数量放到同一行 -->
            <div class="info-row-group">
              <!-- 状态选择 -->
            <div class="form-card status-form-card">
              <label class="form-card-label">状态</label>
              <transition name="fade" mode="out-in">
                <div v-if="!editingStatus" key="display" class="location-display" @click="editingStatus = true">
                  {{ getStatusName(localItem.status) || '-' }}
                </div>
                <el-select
                  v-else
                  key="edit"
                  v-model="localItem.status"
                  placeholder="请选择状态"
                  @change="editingStatus = false"
                  @blur="editingStatus = false"
                  class="edit-input status-select"
                  size="small"
                  popper-class="status-select-dropdown"
                >
                <el-option
                  v-for="status in statuses"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </el-select>
              </transition>
              </div>
              
              <!-- 消耗品开关 -->
              <div class="form-card input-card">
                <label class="form-card-label">是否消耗品</label>
                <el-switch
                  v-model="localItem.isConsumable"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                />
              </div>
              
              <!-- 数量设置 -->
              <div class="form-card input-card">
                <label class="form-card-label">数量</label>
                <div v-if="!editingQuantity" class="location-display" @click="editingQuantity = true">
                  {{ localItem.quantity !== undefined ? localItem.quantity : (localItem.isConsumable === 1 ? 0 : 1) }}
                </div>
                <el-input-number
                  v-else
                  v-model="localItem.quantity"
                  :min="localItem.isConsumable === 1 ? 0 : 1"
                  :step="1"
                  @blur="editingQuantity = false"
                  ref="quantityInput"
                  class="edit-input"
                  size="small"
                />
              </div>
            </div>

            <!-- Card for Notes -->
            <div class="form-card notes-form-card">
              <label class="form-card-label">备注</label>
              <div class="location-display" style="min-height: 60px; white-space: pre-line;">{{ localItem.notes || '-' }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>


<style scoped>
/* --- Modal Overlay & Container --- */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Standard semi-transparent background */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* Ensure it's above other content */
  backdrop-filter: blur(5px); /* Add blur effect */
  will-change: opacity; /* Optimize animation */
}

.modal-container {
  background-color: white;
  border-radius: 16px; /* Larger radius */
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2); /* Softer shadow */
  width: 90%; /* Percentage width */
  max-width: 800px; /* Cap width */
  max-height: 85vh; /* Limit height */
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative; /* Keep relative for loading overlay */
  will-change: transform, opacity; /* Optimize animation */
  transform-origin: center; /* Animation origin */
}

/* --- Transition --- */
.modal-enter-active {
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); /* Spring-like entrance */
}

.modal-leave-active {
  transition: all 0.3s cubic-bezier(0.6, -0.28, 0.735, 0.045); /* Faster exit */
}

.modal-enter-from .modal-container {
  transform: scale(0.7);
  opacity: 0;
}

.modal-enter-to .modal-container {
  transform: scale(1);
  opacity: 1;
}

.modal-leave-from .modal-container {
  transform: scale(1);
  opacity: 1;
}

.modal-leave-to .modal-container {
  transform: scale(0.85);
  opacity: 0;
}

.modal-enter-from, .modal-leave-to {
  opacity: 0; /* Fade overlay */
}

.modal-enter-to, .modal-leave-from {
  opacity: 1; /* Fade overlay */
}

/* --- Modal Header --- */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px; /* Standard padding */
  border-bottom: 1px solid rgba(0, 0, 0, 0.1); /* Lighter border */
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px; /* Buttons between */
}

.modal-title {
  font-size: 1.25rem; /* Slightly smaller than stats */
  font-weight: 600;
  color: #1d1d1f; /* Darker text */
  margin: 0;
}

.save-button {
  border-radius: 6px;
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}

.modal-close {
  background: none;
  border: none;
  width: 32px; /* Standard close button size */
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  transition: background-color 0.2s;
}
.modal-close:hover {
  background-color: rgba(18, 18, 19, 0.05); /* Subtle hover effect */
}

/* --- Modal Content --- */
.modal-content {
  padding: 16px 20px 16px 20px; /* 减少内边距，原来是16px 20px 24px 20px */
  overflow-y: auto; /* Allow content scrolling */
  flex-grow: 1;
  background-color: #f8f9fa; /* Light background for content area */
  font-weight: 500 !important; /* 默认加粗所有文本 */
  font-size: 1.1em !important; /* 默认加大所有文本 */
}

/* --- Loading Indicator --- */
.modal-loading-indicator {
  position: absolute; /* Cover the content area */
  top: 61px; /* Below header */
  left: 0;
  right: 0;
  bottom: 61px; /* Above footer */
  background-color: rgba(255, 255, 255, 0.8); /* Semi-transparent white overlay */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10; /* Above content, below header/footer */
  pointer-events: none; /* Allow interaction with header/footer if needed */
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid rgba(0, 113, 227, 0.1);
  border-top-color: #0071e3;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.modal-loading-indicator p {
  color: #606266;
  font-size: 14px;
}

/* --- Item Display Header (for Icon) --- */
.item-display-header {
  display: none;
}

.header-layout {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 10px; /* 减少下边距，原来是24px */
  padding: 10px 0;
  gap: 30px; /* 增加头像和名称之间的间距 */
  justify-content: flex-start; /* 确保元素靠左对齐 */
  position: relative; /* 添加相对定位，用于定位右上角元素 */
}

/* 右上角分类和位置容器 */
.top-right-info {
  position: absolute;
  top: -5px; /* 向上移动5px */
  right: 0;
  display: flex;
  flex-direction: column;
  gap: 6px; /* 进一步减小间距，原来是8px */
  width: 220px;
}

/* 调整右上角的卡片样式 */
.top-right-info .form-card {
  margin: 0;
  padding: 6px 10px; /* 减小内边距 */
  box-shadow: none;
  border: 1px solid #f0f0f0;
  background-color: #fff;
  border-radius: 8px;
}

/* 调整右上角的标签样式 */
.top-right-info .form-card-label {
  font-size: 14px; /* 减小字体大小 */
  margin-bottom: 4px; /* 减小下边距 */
}

/* 调整右上角的显示值样式 */
.top-right-info .location-display {
  min-height: 32px; /* 减小高度 */
  font-size: 14px; /* 减小字体大小 */
}

/* 调整图标大小和位置 */
.header-layout .icon-box.large-icon {
  flex-shrink: 0; /* 防止图标被压缩 */
  margin: 0; /* 移除之前的边距 */
  width: 120px; /* 增大图标框宽度 */
  height: 120px; /* 增大图标框高度 */
}

/* 调整图标内部元素大小 */
.header-layout .icon-box.large-icon svg,
.header-layout .icon-box.large-icon .el-icon {
  font-size: 52px; /* 增大图标大小 */
  width: 52px;
  height: 52px;
}

/* 名称输入容器 */
.name-input-container {
  flex-grow: 0; /* 不自动扩展 */
  width: 50%; /* 限制宽度，避免与右侧重叠 */
  max-width: 350px; /* 最大宽度限制 */
}

/* 名称标题包装器 */
.name-title-wrapper {
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 名称标题输入框样式 */
.name-title-input {
  width: 100%;
  font-size: 40px;
  font-weight: 900;
  color: #333;
  border: none;
  background: transparent;
  padding: 0;
  margin: 0;
  line-height: 1.2;
  outline: none;
}

.name-title-input::placeholder {
  color: #aaa;
  opacity: 0.7;
}

/* --- Edit Form --- */
.edit-form {
  padding-top: 0; /* 移除顶部内边距，原来是10px */
  display: flex;
  flex-direction: column;
  gap: 6px; /* 进一步减少表单卡片之间的间距，原来是8px */
}

/* --- Info Row Group --- */
.info-row-group {
  display: flex;
  gap: 10px; /* 进一步减少同一行卡片之间的间距，原来是12px */
  margin-bottom: 0;
  margin-top: 6px; /* 减少顶部间距，原来是8px */
}

/* --- Form Card 基础样式 --- */
.form-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 8px 12px; /* 减少内边距，原来是12px 16px */
  border: 1px solid #f0f0f0;
  flex: 1;
}

/* --- 输入卡片样式 --- */
.input-card {
  padding: 4px 12px; /* 减少垂直内边距，原来是6px 16px */
  overflow: hidden;
  border: 1px solid #f0f0f0; /* 添加边框，与其他卡片一致 */
  background-color: #fff; /* 添加背景色，与其他卡片一致 */
  border-radius: 12px;
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 标签和输入框之间留出空间 */
}

/* 日期输入卡片特殊样式 */
.date-input-card {
  padding: 6px 16px; /* 减小垂直内边距 */
  overflow: hidden;
  border: 1px solid #f0f0f0;
  background-color: #fff;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 调整输入框样式 */
:deep(.input-card .clean-input) {
  flex-grow: 1; /* 让输入框占据剩余空间 */
  width: auto !important;
}

/* 强制精确居中Element-Plus的输入框文本 */
:deep(.el-input__wrapper) {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  box-shadow: none !important;
  border: none !important; /* 移除边框 */
  background-color: #fff !important;
  border-radius: 6px !important;
  padding: 0 11px !important;
  height: 32px !important;
}

/* 后缀图标样式优化 */
:deep(.el-input__suffix-inner) {
  margin-left: 0 !important;
  padding-left: 0 !important;
  border-left: none !important;
}

:deep(.el-input__icon) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}

/* 清除按钮样式 */
:deep(.el-input__clear) {
  margin-left: 0 !important;
  padding-left: 0 !important;
  border-left: none !important;
  background: transparent !important;
  color: #c0c4cc !important;
}

/* 下拉框样式优化 */
:deep(.el-select .el-input__wrapper) {
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-select .el-input__suffix) {
  background: transparent !important;
  border: none !important;
}

/* 日期字段标签样式 */
.date-field-label {
  font-size: 15px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 0;
  margin-right: 16px;
}

/* 普通标签样式 */
.form-card-label {
  display: block;
  font-size: 14px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 500;
}

/* 只读卡片样式 */
.readonly-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  padding-bottom: 12px;
}

.readonly-card .form-card-label {
  margin-bottom: 0;
  color: #606266;
}

.form-card-value {
  color: #1d1d1f;
  font-weight: 500;
  font-size: 14px;
}

/* 分类、位置、状态卡片特殊样式 */
.category-form-card,
.location-form-card,
.status-form-card,
.rating-form-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px; /* 调整垂直内边距 */
  /* 保持卡片背景 */
}

.category-form-card .form-card-label,
.location-form-card .form-card-label,
.status-form-card .form-card-label,
.rating-form-card .form-card-label {
  display: inline;
  margin-bottom: 0;
  color: #303133;
  font-size: 15px; /* 增大标签字体 */
  font-weight: 500;
  flex-shrink: 0;
  margin-right: 16px;
}

/* --- Element Plus 组件深度样式 --- */
/* 输入框样式 - 修改为只针对特定元素的样式 */
:deep(.date-input-card .clean-input .el-input__wrapper) {
  border: none !important;
  box-shadow: none !important;
  background-color: #ffffff !important;
  border-radius: 12px !important;
  padding: 12px 16px !important;
  height: auto !important;
}

:deep(.date-input-card .clean-input .el-input__suffix) {
  right: 12px !important;
}

:deep(.clean-input .el-input__clear) {
  color: #c0c4cc !important;
  right: 12px !important;
}

:deep(.date-input-card .clean-input input) {
  font-size: 16px !important;
  height: 24px !important;
  color: #303133 !important;
}

/* 下拉框样式 (新样式) */
:deep(.category-select) {
  flex-grow: 1;
  width: auto !important;
}

:deep(.category-form-card .el-input__wrapper),
:deep(.location-form-card .el-input__wrapper),
:deep(.status-form-card .el-input__wrapper) {
  padding: 1px 11px !important; /* 恢复 Element Plus 默认内边距 */
  text-align: left !important; /* 文本左对齐 */
  border: 1px solid #dcdfe6 !important; /* 添加边框 */
  box-shadow: none !important;
  background-color: #fff !important; /* 设置白色背景 */
  border-radius: 6px !important; /* 添加圆角 */
  cursor: pointer;
  height: 32px !important; /* 固定高度 */
}

/* 保持选中项的默认样式或根据需要微调 */
:deep(.category-select .el-select__selected-item span){
     color: #303133; /* 选中值的颜色 */
     font-weight: normal;
}

:deep(.category-select .el-select__suffix-inner .el-icon) {
  color: #909399;
  font-size: 14px; /* 稍微调整箭头大小 */
}

/* 日期选择器样式调整 */
:deep(.clean-date-picker) {
  flex-grow: 1;
  width: auto !important;
}

:deep(.clean-date-picker .el-input__wrapper) {
  padding: 0 11px !important;
  border: 1px solid #dcdfe6 !important;
  box-shadow: none !important;
  background-color: #fff !important;
  border-radius: 6px !important;
  height: 32px !important;
  display: flex !important;
  align-items: center !important;
}

:deep(.clean-date-picker .el-input__inner) {
  height: 30px !important;
  line-height: 30px !important;
  padding: 0 !important;
  font-size: 14px !important;
}

/* 备注卡片的特殊样式 */
.notes-form-card {
  display: flex;
  flex-direction: column; /* 文本区域比较高，采用纵向布局 */
  padding: 10px 16px;
}

/* 备注文本区域样式 */
:deep(.notes-form-card .el-textarea) {
  margin-top: 8px; /* 增加标签和文本区域之间的间距 */
}

:deep(.notes-form-card .el-textarea__inner) {
  min-height: 60px;
  padding: 8px 12px !important;
  background-color: #fff !important;
  resize: none;
  border: 1px solid #dcdfe6 !important;
  box-shadow: none !important;
  border-radius: 6px !important;
}

/* --- 响应式调整 --- */
@media (max-width: 768px) {
  /* 在中等屏幕上，允许卡片组内的卡片换行 */
  .info-row-group {
    flex-wrap: wrap;
  }
  .form-card:not(.full-width-card) {
    flex-basis: calc(50% - 8px);
  }
}

@media (max-width: 600px) {
  .modal-container {
    width: 95%;
    max-height: 90vh;
  }
  
  .icon-box.large-icon {
    width: 80px;
    height: 80px;
  }
  
  .info-row-group {
    flex-direction: column;
    gap: 12px;
  }
  
  .form-card {
    padding: 10px 14px;
    border-radius: 10px;
    flex-basis: auto !important;
  }
  
  :deep(.clean-input .el-input__wrapper) {
    padding: 10px 14px !important;
  }
  
  :deep(.clean-input input) {
    font-size: 15px !important;
  }
  
  .date-field-label {
    padding: 12px 14px 8px;
  }
  
  :deep(.clean-date-picker .el-input__wrapper) {
    padding: 4px 14px 10px !important;
  }
  
  :deep(.clean-date-picker .el-input__inner) {
    font-size: 15px !important;
  }
  
  .form-card-label {
    font-size: 14px;
    margin-bottom: 6px;
  }
  
  .category-form-card .form-card-label,
  .location-form-card .form-card-label,
  .status-form-card .form-card-label {
    font-size: 14px;
    margin-right: 10px;
  }
  
  :deep(.category-form-card .el-input__wrapper),
  :deep(.location-form-card .el-input__wrapper),
  :deep(.status-form-card .el-input__wrapper) {
    height: 30px !important; /* 调整小屏幕下的高度 */
    padding: 1px 8px !important; /* 调整小屏幕下的内边距 */
  }
  
  .header-actions {
    gap: 8px; /* 小屏幕下减少按钮间距 */
  }
  
  .save-button {
    padding: 6px 12px; /* 小屏幕下减小按钮内边距 */
    font-size: 13px;
  }
  
  /* 调整输入卡片在小屏幕上的布局 */
  .input-card, 
  .date-input-card {
    flex-direction: column; /* 在小屏幕上改为纵向排列 */
    align-items: flex-start; /* 左对齐 */
    padding: 10px 14px;
  }
  
  .input-card .form-card-label,
  .date-input-card .form-card-label {
    margin-bottom: 8px; /* 增加标签和输入框之间的间距 */
    margin-right: 0; /* 移除水平间距 */
  }
  
  :deep(.input-card .clean-input),
  :deep(.date-input-card .clean-date-picker) {
    width: 100% !important; /* 让输入框占满整个宽度 */
  }
}

/* 评分组件样式 */
:deep(.rating-input) {
  display: inline-flex;
  margin-left: 8px;
}

:deep(.rating-input .el-rate__text) {
  margin-left: 8px;
  font-size: 14px;
  color: #909399;
}

:deep(.rating-input .el-rate__item) {
  margin-right: 4px;
}

/* 位置选择器的自定义样式 */
:deep(.location-form-card .el-select.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409EFF inset !important;
}

:deep(.location-form-card .el-input__wrapper input) {
  font-size: 14px !important;
  height: 28px !important;
}

:deep(.el-input input.el-input__inner) {
  /* 重置所有可能影响垂直对齐的属性 */
  padding: 0 !important;
  margin: 0 !important;
  line-height: 1 !important; /* 使用1作为基础行高 */
  height: auto !important; /* 让内容决定高度 */
  font-size: 14px !important;
  /* 防止其他CSS属性影响 */
  position: static !important;
  transform: none !important;
  top: auto !important;
}

/* 日期选择器样式 */
:deep(.el-date-editor.el-input) {
  width: 100% !important;
}

:deep(.el-date-editor .el-input__wrapper) {
  display: flex !important;
  align-items: center !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-date-editor .el-input__inner) {
  padding: 0 !important;
  margin: 0 !important;
  height: auto !important;
  line-height: 1 !important;
  font-size: 14px !important;
}

/* 移除所有输入框中的分隔线和边框 */
:deep(.el-input__suffix) {
  border-left: none !important;
  background: transparent !important;
}

/* 为了解决特定问题，移除可能的边框 */
:deep(.el-input .el-input__wrapper) {
  border: none !important;
  box-shadow: none !important;
}

/* 标签文本增强 */
.form-card-label {
  font-weight: 600 !important; /* 更粗的标签文本 */
  font-size: 16px !important; /* 加大标签文字 */
  color: #303133 !important; /* 确保清晰可见的颜色 */
}

/* 输入框文本增强 */
:deep(.el-input__inner) {
  font-weight: 500 !important; /* 加粗输入框文本 */
  font-size: 16px !important; /* 加大输入框文字 */
}

/* 标题文本增强 */
.modal-title {
  font-weight: 700 !important; /* 标题更粗 */
  font-size: 1.4rem !important; /* 加大标题 */
}

/* 按钮文本增强 */
.save-button {
  font-weight: 600 !important; /* 按钮文字加粗 */
  font-size: 15px !important; /* 按钮文字加大 */
}

/* 下拉选择器文本增强 */
:deep(.el-select .el-select__inner),
:deep(.el-select-dropdown__item) {
  font-weight: 500 !important; /* 下拉选项加粗 */
  font-size: 16px !important; /* 下拉选项加大 */
}

/* 日期选择器文本增强 */
:deep(.el-date-editor .el-input__inner) {
  font-weight: 500 !important; /* 日期文本加粗 */
  font-size: 16px !important; /* 日期文本加大 */
}

/* 只读字段值增强 */
.form-card-value {
  font-weight: 600 !important; /* 加粗 */
  font-size: 16px !important; /* 加大 */
}

/* 图标样式 */
.icon-box.large-icon {
  width: 96px; /* 更大的图标框 */
  height: 96px;
  border-radius: 12px; /* 更方正的圆角 */
  background-color: #f5f7fa; /* 浅灰色背景，与图片一致 */
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: none; /* 移除阴影 */
  font-size: 40px;
  color: #333;
  position: relative; /* 添加相对定位用于提示文本定位 */
  transition: all 0.2s ease; /* 添加过渡效果 */
  overflow: hidden; /* 隐藏溢出内容 */
}

.icon-box.large-icon:hover {
  background-color: #e6f7ff; /* 鼠标悬停时的背景色 */
  box-shadow: 0 0 10px rgba(0, 122, 255, 0.3); /* 悬停时添加阴影 */
}

.icon-select-hint {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  padding: 3px 0;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.icon-box.large-icon:hover .icon-select-hint {
  opacity: 1;
}

.location-display {
  padding: 8px 12px;
  border-radius: 8px;
  background-color: #f9f9f9;
  min-height: 40px;
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #333;
}

.location-display:hover {
  background-color: #f0f9ff;
  cursor: pointer;
}

/* 编辑状态下的输入框样式 */
.edit-input {
  border: none;
  box-shadow: none;
  width: auto !important; /* 使宽度自适应内容 */
  max-width: 120px; /* 减小最大宽度 */
}

:deep(.edit-input .el-input__wrapper) {
  background-color: #f9f9f9;
  padding: 2px 6px !important; /* 进一步减小内边距 */
  border-radius: 6px;
  min-height: 30px !important; /* 进一步减小高度 */
  box-shadow: none !important;
  border: 1px solid #e0e0e0 !important;
  display: flex;
  align-items: center; /* 文本垂直居中 */
}

:deep(.edit-input .el-input__inner) {
  height: auto !important;
  line-height: normal !important;
  font-size: 18px !important;
  padding: 0 2px !important; /* 减小内部文本的内边距 */
}

/* 日期选择器特有的样式 */
.date-picker {
  width: auto !important;
}

:deep(.edit-input.date-picker .el-input__wrapper) {
  padding: 0 6px !important;
}

:deep(.edit-input.date-picker .el-input__inner) {
  width: 60px !important;
}

/* 状态下拉框特有的样式 */
.status-select {
  width: auto !important;
}

:deep(.edit-input.status-select .el-input__wrapper) {
  padding: 0 6px !important;
}

:deep(.edit-input.status-select .el-input__inner) {
  width: 100px !important;
}

/* 状态下拉框的淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-5px);
}

/* 调整下拉选择器样式 */
:deep(.status-select-dropdown) {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  animation: dropdown-in 0.2s ease-out;
}

@keyframes dropdown-in {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 优化选择框样式 */
:deep(.edit-input.status-select .el-input__wrapper) {
  transition: all 0.3s ease;
  border-color: #dcdfe6;
}

:deep(.edit-input.status-select:hover .el-input__wrapper) {
  border-color: #c0c4cc;
}

/* 优化下拉选项样式 */
:deep(.status-select-dropdown .el-select-dropdown__item) {
  padding: 8px 12px;
  font-size: 14px;
  transition: all 0.2s ease;
}

:deep(.status-select-dropdown .el-select-dropdown__item.selected) {
  font-weight: 600;
  color: #409eff;
  background-color: #ecf5ff;
}

:deep(.status-select-dropdown .el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

/* 优化状态显示样式，鼠标悬停时添加提示效果 */
.location-display {
  transition: all 0.2s ease;
}

.location-display:hover {
  background-color: #f0f9ff;
  cursor: pointer;
  box-shadow: 0 0 0 1px #e6f2ff;
}

/* 消耗品开关样式 */
:deep(.el-switch) {
  --el-switch-on-color: #34c759;
}
</style> 